package com.zhaolang.qogir.db;

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import com.zhaolang.qogir.db.dao.impl.AuthDaoImpl;

/**
 * 
 * @author hj
 * @time 2015-03-16
 *
 */
public class DBHelper extends SQLiteOpenHelper {
	private final String TAG = "DBHelper.class";
	private static final String DBNAME = "skin.db";
	private static final int VERSION = 21;
	private static DBHelper dbHelper;

	public static DBHelper getInstance(Context context) {
		if (dbHelper == null) {
			synchronized (DBHelper.class) { 
				if (dbHelper == null) { 
					dbHelper = new DBHelper(context);
				}
			}
		}
		return dbHelper;
	}

	public DBHelper(Context context) {
		super(context, DBNAME, null, VERSION);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {

		onCreatePostList(db);
		onCreatePostType(db);
		onCreatePostsDetail(db);
		onCreateAnswer(db);
	}

	private void onCreateAnswer(SQLiteDatabase db) {
		try {
			db.execSQL("DROP TABLE IF EXISTS " + "answer");
			String sql = "CREATE TABLE answer(_id INTEGER PRIMARY KEY," + "postdetail_id  TEXT ," + "user_id TEXT ,"
					+ "floor_id  TEXT," + "item_json   TEXT);";
			db.execSQL(sql);
		} catch (SQLException e) {
			Log.e("hj", "creat table answer is erros");
		}
	}

	private void onCreatePostsDetail(SQLiteDatabase db) {
		try {
			db.execSQL("DROP TABLE IF EXISTS " + "postdetail");
			String sql = "CREATE TABLE postsdetail(_id INTEGER PRIMARY KEY," + "postdetail_id     TEXT ,"
					+ "item_json   TEXT);";
			db.execSQL(sql);
		} catch (SQLException e) {
			Log.e("hj", "creat table posttype is erros");
		}
	}

	private void onCreatePostType(SQLiteDatabase db) {
		try {
			db.execSQL("DROP TABLE IF EXISTS " + "posttype");
			String sql = "CREATE TABLE posttype(_id INTEGER PRIMARY KEY," + "type_id  INTEGER," + "type_name   TEXT);";
			db.execSQL(sql);
		} catch (SQLException e) {
			Log.e("hj", "creat table posttype is erros");
		}
	}

	private void onCreatePostList(SQLiteDatabase db) {
		try {
			db.execSQL("DROP TABLE IF EXISTS " + "postlist");
			String sql = "CREATE TABLE postlist( _id INTEGER PRIMARY KEY," + "type_id    INTEGER,"
					+ "postdetail_id    TEXT);";
			db.execSQL(sql);
		} catch (SQLException e) {
			Log.e("hj", "crate table postlist is errors");
		}
	}

	private void onCreateAuth(SQLiteDatabase db) {
		try {
			db.execSQL(AuthDaoImpl.CREATE_USER_TABLE);
		} catch (Exception e) {
			Log.e(TAG, "create table auth is errors");
		}
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

		if (oldVersion < newVersion) {
			onCreate(db);
		}

	}

}
